package com.zzh.oauth.intergration.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

@Component
@Slf4j
public class U2Service {
    @Value("${u2.oauth2.client-id}")
    private String clientId;

    @Value("${u2.oauth2.client-secret}")
    private String clientSecret;

    @Value("${u2.oauth2.callback-url}")
    private String callbackUrl;

    @Value("${u2.authorize-url}")
    private String authorizeUrl;

    @Value("${u2.access-token-url}")
    private String accessTokenUrl;

    @Value("${u2.access-token-verify-url}")
    private String accessTokenVerifyUrl;

    @Autowired
    private RestTemplate restTemplate;


    public  String getAccessToken(String code, String state){
        log.error("获取token，code={}, state={}",code,state);
        //固定值
        String method = "GetAccessToken";

        MultiValueMap<String, String> params = new LinkedMultiValueMap<>(7);
        params.add("grant_type", "authorization_code");
        params.add("code", code);
        params.add("client_id", clientId);
        params.add("client_secret", clientSecret);
        params.add("redirect_uri", callbackUrl);
        //用于防止CSRF
        params.add("state", state);
        params.add("method", method);

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        headers.add("User-Agent", "Top4Net");

        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(params, headers);

        ResponseEntity<String> response = restTemplate.postForEntity(accessTokenUrl, httpEntity, String.class);
        String resultStr = response.getBody();
        log.debug("u2授权登录返回{}", resultStr);
        return resultStr;

    }
}
